<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:pls="http://www.w3.org/2005/01/pronunciation-lexicon" xmlns:ssml="http://www.w3.org/2001/10/synthesis" xmlns:svg="http://www.w3.org/2000/svg">
  <head>
    <title>Calling Java methods from Scheme</title>
    <link rel="stylesheet" type="text/css" href="docbook-epub.css"/>
    <link rel="stylesheet" type="text/css" href="kawa.css"/>
    <script src="kawa-ebook.js" type="text/javascript"/>
    <meta name="generator" content="DocBook XSL-NS Stylesheets V1.79.1"/>
    <link rel="prev" href="Overall-Index.xhtml" title="Index"/>
    <link rel="next" href="Allocating-objects.xhtml" title="Allocating objects"/>
  </head>
  <body>
    <header/>
    <section class="sect1" title="Calling Java methods from Scheme" epub:type="subchapter" id="Method-operations">
      <div class="titlepage">
        <div>
          <div>
            <h2 class="title" style="clear: both">Calling Java methods from Scheme</h2>
          </div>
        </div>
      </div>
      <p>You can call a Java method as if it were a Scheme procedure
using various mechanisms.
</p>
      <section class="sect2" title="Calling static methods using colon notation" epub:type="division" id="idm139667871098400">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Calling static methods using colon notation</h3>
            </div>
          </div>
        </div>
        <p>The easiest way to invoke a static method is to use
<a class="link" href="Colon-notation.xhtml" title="Property access using colon notation">colon notation</a>, specifically:
</p>
        <div class="literallayout">
          <p><code class="literal"><span class="bold"><strong>(</strong></span></code><em class="replaceable"><code>class-expression</code></em><code class="literal"><span class="bold"><strong>:</strong></span></code><em class="replaceable"><code>method-name</code></em> <em class="replaceable"><code>argument</code></em> ...<code class="literal"><span class="bold"><strong>)</strong></span></code><br/>
</p>
        </div>
        <p>The <em class="replaceable"><code>class-expression</code></em> can be a class in the current lexical
scope, such as a class defined using <code class="literal">define-simple-class</code>:
</p>
        <pre class="screen">(define-simple-class MyClass ()
  ((add2 x y) allocation: 'static (+ x y)))
(MyClass:add2 3 4) ⇒ 7
</pre>
        <p>Often <em class="replaceable"><code>class-expression</code></em> is a fully-qualified class name:
</p>
        <pre class="screen">(java.lang.Math:sqrt 9.0) ⇒ 3.0
</pre>
        <p>This is only allowed when the name is of a class that exists
and is accessible both at compile-time and run-time,
and the name is not otherwise lexically bound.
</p>
        <p>You can also use a defined alias:
</p>
        <pre class="screen">(define-alias jlMath java.lang.Math)
(jlMath:sqrt 16.0) ⇒ 4.0
</pre>
        <p>You can even evaluate <em class="replaceable"><code>class-expression</code></em> at run-time
(in which case Kawa may have to use slower reflection):
</p>
        <pre class="screen">(let ((math java.lang.Math)) math:sqrt 9.0) ⇒ 3.0
</pre>
        <p>Here <code class="literal">java.lang.Math</code> evaluates to a <code class="literal">java.lang.Class</code>
instance for the named class (like Java’s <code class="literal">java.lang.Class.class</code>,
again assuming the class exists and is accessible both at compile-time and
run-time, and the name is not otherwise lexically bound.
</p>
      </section>
      <section class="sect2" title="Calling instance methods using colon notation" epub:type="division" id="idm139667871085136">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Calling instance methods using colon notation</h3>
            </div>
          </div>
        </div>
        <p>The syntax is:
</p>
        <div class="literallayout">
          <p><code class="literal"><span class="bold"><strong>(</strong></span></code><em class="replaceable"><code>instance</code></em><code class="literal"><span class="bold"><strong>:</strong></span></code><em class="replaceable"><code>method-name</code></em> <em class="replaceable"><code>argument</code></em> ...<code class="literal"><span class="bold"><strong>)</strong></span></code><br/>
</p>
        </div>
        <p>This invokes the method named <em class="replaceable"><code>method-name</code></em>
with the evaluated  <em class="replaceable"><code>instance</code></em> as the target object
and the evaluated <em class="replaceable"><code>argument</code></em>s as the method arguments.
</p>
        <p>For example:
</p>
        <pre class="screen">((list 9 8 7):toString) ⇒ "(9 8 7)"
([5 6 7]:get 2) ⇒ 7
</pre>
        <p>This older syntax is also available:
</p>
        <div class="literallayout">
          <p><code class="literal"><span class="bold"><strong>(*:</strong></span></code><em class="replaceable"><code>method-name</code></em> <em class="replaceable"><code>instance</code></em> <em class="replaceable"><code>argument</code></em> ...<code class="literal"><span class="bold"><strong>)</strong></span></code><br/>
</p>
        </div>
        <p>For example:
</p>
        <pre class="screen">(*:toString (list 9 8 7))
</pre>
        <p>You can also name the class explicitly:
</p>
        <div class="literallayout">
          <p><code class="literal"><span class="bold"><strong>(</strong></span></code><em class="replaceable"><code>class-expression</code></em><code class="literal"><span class="bold"><strong>:</strong></span></code><em class="replaceable"><code>method-name</code></em> <em class="replaceable"><code>instance</code></em> <em class="replaceable"><code>argument</code></em> ...<code class="literal"><span class="bold"><strong>)</strong></span></code><br/>
</p>
        </div>
        <p>For example:
</p>
        <pre class="screen">(java.util.List:get [5 6 7] 2) ⇒ 7
</pre>
        <p>Using an explicit class is like coercing the <em class="replaceable"><code>instance</code></em>:
</p>
        <div class="literallayout">
          <p><code class="literal"><span class="bold"><strong>(*:</strong></span></code><em class="replaceable"><code>method-name</code></em> <code class="literal"><span class="bold"><strong>(as </strong></span></code><em class="replaceable"><code>class-expression</code></em> <em class="replaceable"><code>instance</code></em> <code class="literal"><span class="bold"><strong>)</strong></span></code><em class="replaceable"><code>argument</code></em> ...<code class="literal"><span class="bold"><strong>)</strong></span></code><br/>
</p>
        </div>
        <p>Note that for some special values,
including <code class="literal">java.lang.Class</code> instances, you can’t
use the compact form of <a class="link" href="Colon-notation.xhtml" title="Property access using colon notation">colon notation</a>
where the <em class="replaceable"><code>instance</code></em> is before the comma:
</p>
        <pre class="screen">(java.lang.Integer:getDeclaredField "MAX_VALUE") ⇒ <span class="emphasis"><em>error</em></span>
</pre>
        <p>This is because in this case we look for a static member
of <code class="literal">java.lang.Integer</code>
(at least as currently defined and implemented),
while we want an instance member of <code class="literal">java.lang.Class</code>.
In those cases you can use one of
these alternative forms, which all return the same
<code class="literal">java.lang.reflect.Field</code> result:
</p>
        <pre class="screen">(*:getDeclaredField java.lang.Integer "MAX_VALUE")
(java.lang.Class:getDeclaredField java.lang.Integer "MAX_VALUE")
(invoke java.lang.Integer 'getDeclaredField "MAX_VALUE")
</pre>
      </section>
      <section class="sect2" title="Method names" epub:type="division" id="idm139667871058224">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Method names</h3>
            </div>
          </div>
        </div>
        <p>The method to invoke is selected using the specified
method name and argments.  If specified name is not a Java name,
it is "mangled" (see <a class="link" href="Mangling.xhtml" title="Mapping Scheme names to Java names">Mangling</a>) into a valid Java name.
All accessible methods whose names match are considered.
Methods that match after appending <code class="literal">$V</code> or <code class="literal">$X</code> or <code class="literal">$V$X</code>
are also considered.  A <code class="literal">$V</code> suffix matches a variable
number of arguments:  any excess arguments are collect into an
<code class="literal">gnu.lists.LList</code> or a Java array (depending on the final parameter type).
A <code class="literal">$X</code> specifies that the method expects an extra implicit
<code class="literal">CallContext</code> parameter.  In that case the method’s result is written
to the <code class="literal">CallContext</code>, so the method result type must be <code class="literal">void</code>.
</p>
        <p>(Kawa may compile a procedure with a <code class="literal">#!rest</code> or keyword args
whose name is <code class="literal"><em class="replaceable"><code>fn</code></em></code> to a method named <code class="literal"><em class="replaceable"><code>fn</code></em>$V</code>.
It adds an implicit parameter for the extra arguments.
By default this extra extra parameter is a Scheme list.
You can specify a Java array type instead, in which case the method is
named <code class="literal"><em class="replaceable"><code>fn</code></em></code> without the <code class="literal">$V</code>,
and instead it is marked as a Java-5 varargs method.
The array element type must be compatible with all the extra arguments.)
</p>
      </section>
      <section class="sect2" title="Invoking a method with the invoke function" epub:type="division" id="idm139667871048192">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Invoking a method with the <code class="literal">invoke</code> function</h3>
            </div>
          </div>
        </div>
        <p>If you prefer, you can instead use the following functions.
(There is also an older deprecated lower-level interface
(see <a class="link" href="Low-level-functions.xhtml#Low-level-Method-invocation">Low-level Method invocation</a>.)
</p>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667871045408" class="indexterm"/> <code class="function">invoke-static</code> <em class="replaceable"><code>class</code></em> <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>args</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>The <em class="replaceable"><code>class</code></em> can be a <code class="literal">java.lang.Class</code>, a
<code class="literal">gnu.bytecode.ClassType</code>, or a <code class="literal">symbol</code> or <code class="literal">string</code>
that names a Java class.  The <em class="replaceable"><code>name</code></em> can be <code class="literal">symbol</code> or
<code class="literal">string</code> that names one or more methods in the Java class.
</p>
            <p>Any accessible methods (static or instance) in the specified <em class="replaceable"><code>class</code></em>
(or its super-classes) that match "<em class="replaceable"><code>name</code></em>" or "<em class="replaceable"><code>name</code></em>$V" collectively
form a generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the first actual argument is used as the <code class="literal">this</code> argument.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, <code class="literal">WrongType</code> is thrown.
</p>
            <p>An example:
</p>
            <pre class="screen">(invoke-static java.lang.Thread 'sleep 100)
</pre>
            <p>The behavior of interpreted code and compiled code is not
identical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the <code class="literal">invoke-static</code> call
if it can pick a single "best" matching method.
</p>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667871031504" class="indexterm"/> <code class="function">invoke</code> <em class="replaceable"><code>object</code></em> <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>args</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>The <em class="replaceable"><code>name</code></em> can be <code class="literal">&lt;symbol&gt;</code> or
<code class="literal">&lt;string&gt;</code> that names one or more methods in the Java class.
</p>
            <p>Any accessible methods (static or instance) in the specified <em class="replaceable"><code>class</code></em>
(or its super-classes) that match "<em class="replaceable"><code>name</code></em>" or "<em class="replaceable"><code>name</code></em>$V" collectively
form a generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the <em class="replaceable"><code>object</code></em> is used as the <code class="literal">this</code> argument;
otherwise <em class="replaceable"><code>object</code></em> is prepended to the <em class="replaceable"><code>args</code></em> list.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, <code class="literal">WrongType</code> is thrown.
</p>
            <p>The behavior of interpreted code and compiled code is not
indentical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the <code class="literal">invoke-static</code> call
if it can pick a single "best" matching method.
</p>
            <p>If the compiler cannot determine the method to call (assuming
the method name is constant), the compiler has to generate code
at run-time to find the correct method.  This is much slower,
so the compiler will print a warning.  To avoid a waning, you can
use a type declaration, or insert a cast:
</p>
            <pre class="screen">(invoke (as java.util.Date my-date) 'setDate cur-date)
</pre>
            <p>or
</p>
            <pre class="screen">(let ((my-date ::java.util.Date (calculate-date))
      (cur-date ::int (get-cur-date)))
  (invoke my-date 'setDate cur-date))
</pre>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667871017632" class="indexterm"/> <code class="function">invoke-special</code> <em class="replaceable"><code>class</code></em> <em class="replaceable"><code>receiver-object</code></em> <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>arg</code></em> <em class="replaceable"><code>...</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>The <em class="replaceable"><code>class</code></em> can be a <code class="literal">java.lang.Class</code>, a
<code class="literal">gnu.bytecode.ClassType</code>, or a <code class="literal">symbol</code> or <code class="literal">string</code>
that names a Java class.  
The <em class="replaceable"><code>name</code></em> can be <code class="literal">symbol</code> or
<code class="literal">string</code> that names one or more methods in the Java class.
</p>
            <p>This procedure is very similar to <code class="literal">invoke</code> and <code class="literal">invoke-static</code>
and invokes the specified method, ignoring any methods in subclasses
that might overide it.  One interesting use is to invoke a method in
your super-class like the Java language <code class="literal">super</code> keyword.
</p>
            <p>Any methods in the specified <em class="replaceable"><code>class</code></em> that match "<em class="replaceable"><code>name</code></em>" or
"<em class="replaceable"><code>name</code></em>$V" collectively form a generic procedure.  That generic
procedure is then applied as in <code class="literal">invoke</code> using the
<code class="literal">receiver-object</code> and the arguments (if any).
</p>
            <p>The compiler must be able to inline this procedure (because you cannot
force a specific method to be called using reflection).  Therefore the
<em class="replaceable"><code>class</code></em> and <em class="replaceable"><code>name</code></em> must resolve at compile-time to a specific
method.
</p>
            <pre class="screen">(define-simple-class &lt;MyClass&gt; (&lt;java.util.Date&gt;)
  ((get-year) :: &lt;int&gt;
   (+ (invoke-special &lt;java.util.Date&gt; (this) 'get-year)) 1900)
  ((set-year (year :: &lt;int&gt;)) :: &lt;void&gt;
   (invoke-special &lt;java.util.Date&gt; (this) 'set-year (- year 1900))))
</pre>
          </blockquote>
        </div>
        <p class="synopsis" kind="Procedure"><span class="kind">Procedure</span><span class="ignore">: </span><a id="idm139667871002000" class="indexterm"/> <code class="function">class-methods</code> <em class="replaceable"><code>class</code></em> <em class="replaceable"><code>name</code></em></p>
        <div class="blockquote">
          <blockquote class="blockquote">
            <p>Return a generic function containing those methods of <em class="replaceable"><code>class</code></em>
that match the name <em class="replaceable"><code>name</code></em>, in the sense of <code class="literal">invoke-static</code>.
Same as:
</p>
            <pre class="screen">(lambda args (apply invoke-static (cons class (cons name args))))
</pre>
          </blockquote>
        </div>
        <p>Some examples using these functions are ‘<code class="literal">vectors.scm</code>’
and ‘<code class="literal">characters.scm</code>’ the directory ‘<code class="literal">kawa/lib</code>’ in
the Kawa sources.
</p>
      </section>
      <section class="sect2" title="Using a namespace prefix" epub:type="division" id="idm139667870994624">
        <div class="titlepage">
          <div>
            <div>
              <h3 class="title">Using a namespace prefix</h3>
            </div>
          </div>
        </div>
        <p><span class="emphasis"><em>This way of invoking a method is deprecated.</em></span>
</p>
        <p>You can use <code class="literal">define-namespace</code> to define an alias for a Java class:
</p>
        <pre class="screen">(define-namespace Int32 "class:java.lang.Integer")
</pre>
        <p>In this example the name <code class="literal">Int32</code> is a <em class="firstterm">namespace alias</em>
for the namespace whose full name is <code class="literal">"class:java.lang.Integer"</code>.
The full name should be the 6 characters <code class="literal">"class:"</code> followed
by the fully-qualified name of a Java class.
</p>
        <p>Instead of a <em class="replaceable"><code>vamespace-uri</code></em> you can use a variable that names
a class, usually of the form <code class="literal">&lt;<em class="replaceable"><code>classname</code></em>&gt;</code>.
The following is equivalent to the above:
</p>
        <pre class="screen">(define-namespace Int32 &lt;java.lang.Integer&gt;)
</pre>
        <p>However, there is one important difference: The <code class="literal">&lt;<em class="replaceable"><code>classname</code></em>&gt;</code>
is first searched in the lexical scope.
It may resolve to a class defined in the current compilation unit
(perhaps defined using <code class="literal">define-simple-class</code>),
or imported from another module,
or an alias (such as from <code class="literal">define-alias</code>).
Only if <code class="literal">&lt;<em class="replaceable"><code>classname</code></em>&gt;</code> is <span class="emphasis"><em>not</em></span> found in the current
scope is it tried as the class name <em class="replaceable"><code>classname</code></em>.
</p>
        <p>You can name a method using a <em class="firstterm">qualified name</em> containing a colon.
The part of the name before the colon is a namespace alias (in
this case <code class="literal">Int32</code>), and the part of the name after the colon is the
method name.  For example:
</p>
        <pre class="screen">(Int32:toHexString 255) ⇒ "ff"
</pre>
        <p>This invokes the static method <code class="literal">toHexString</code> in the
Java class <code class="literal">java.lang.Integer</code>, passing it the argument <code class="literal">255</code>,
and returning the String <code class="literal">"ff"</code>.
</p>
        <p>The general syntax is
</p>
        <pre class="screen">(<em class="replaceable"><code>prefix</code></em>:<em class="replaceable"><code>method-name</code></em> <em class="replaceable"><code>arg</code></em> ...)
</pre>
        <p>This invokes the method named <em class="replaceable"><code>method-name</code></em> in the class corresponding
to <em class="replaceable"><code>prefix</code></em>, and the <em class="replaceable"><code>arg</code></em>s are the method arguments.
</p>
        <p>You can use the method name <code class="literal">new</code> to construct new objects:
</p>
        <pre class="screen">(Int32:new '|255|)
</pre>
        <p>This is equivalent to the Java expression <code class="literal">new Integer("255")</code>.
You can also write:
</p>
        <pre class="screen">(Int32:new "255")
</pre>
        <p>You can also call instance methods using a namespace prefix:
</p>
        <pre class="screen">(Int32:doubleValue (Int32:new "00255"))
</pre>
        <p>This returns the <code class="literal">double</code> value <code class="literal">255.0</code>.
</p>
        <p>As a shorthand, you can use the name of a Java class instead of a
namespace alias:
</p>
        <pre class="screen">(java.lang.Integer:toHexString 255)
(java.lang.Object:toString some-value)
</pre>
        <p>If Kawa sees a qualified name with a prefix that is not defined <span class="emphasis"><em>and</em></span>
that matches the name of a known class, then Kawa will automatically
treat the prefix
as a nickname for namespace uri like <code class="literal">class:java.lang.Integer</code>.
Both conditions should be true at both compile-time and run-time.
However, using an explicit <code class="literal">define-namespace</code> is recommended.
</p>
        <p>As a final shorthand you can use an identifier in handle brackets,
such as an existing type alias like <code class="literal">&lt;list&gt;</code>.
The following are all equivalent:
</p>
        <pre class="screen">(&lt;list&gt;:list3 'a 'b 'c)
</pre>
        <p>This is equivalent to:
</p>
        <pre class="screen">(define-namespace <em class="replaceable"><code>prefix</code></em> &lt;list&gt;
(<em class="replaceable"><code>prefix</code></em>:list3 'a 'b 'c)
</pre>
        <p>for some otherwise-unused <em class="replaceable"><code>prefix</code></em>.
</p>
      </section>
    </section>
    <footer>
      <div class="navfooter">
        <ul>
          <li>
            <b class="toc">
              <a href="Method-operations.xhtml#idm139667871098400">Calling static methods using colon notation</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Method-operations.xhtml#idm139667871085136">Calling instance methods using colon notation</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Method-operations.xhtml#idm139667871058224">Method names</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Method-operations.xhtml#idm139667871048192">Invoking a method with the <code class="literal">invoke</code> function</a>
            </b>
          </li>
          <li>
            <b class="toc">
              <a href="Method-operations.xhtml#idm139667870994624">Using a namespace prefix</a>
            </b>
          </li>
        </ul>
        <p>
          Up: <a accesskey="u" href="Objects-Classes-and-Modules.xhtml">Object, Classes and Modules</a></p>
        <p>
        Previous: <a accesskey="p" href="Dynamic-records.xhtml">Creating New Record Types On-the-fly</a></p>
        <p>
        Next: <a accesskey="n" href="Allocating-objects.xhtml">Allocating objects</a></p>
      </div>
    </footer>
  </body>
</html>
